package htime

import (
	"regexp"
	"time"
)

func init() {
	Register(newHDateTimeYmdHis())
}

type hDateTimeYmdHis struct {
	*regexp.Regexp
}

func newHDateTimeYmdHis() StrToTime {
	return &hDateTimeYmdHis{Regexp: regexp.MustCompile(`^((1\d{3}|\d{4})((0\d{1}|10|11|12)(([0-2]\d{1}|30|31)(([0-1]\d{1}|20|21|22|23)(([0-5]\d{1})([0-5]\d{1}){0,1}){0,1}){0,1}){0,1}){0,1})$`)}
}

func (h *hDateTimeYmdHis) Check(s string) bool {
	return h.FindStringIndex(s) != nil
}

func (h *hDateTimeYmdHis) Result(strTime *StrTime) *time.Time {
	switch len(strTime.DateTime) {
	case 4:
		return getYmdHis(strTime.DateTime+"01"+"01", getLoc(strTime))
	case 6:
		return getYmdHis(strTime.DateTime+"01", getLoc(strTime))
	case 8:
		return getYmdHis(strTime.DateTime, getLoc(strTime))
	case 10:
		return getYmdHis01(strTime.DateTime+"0000", getLoc(strTime))
	case 12:
		return getYmdHis01(strTime.DateTime+"00", getLoc(strTime))
	case 14:
		return getYmdHis01(strTime.DateTime, getLoc(strTime))
	}
	return nil
}

func getYmdHis(s string, loc *time.Location) *time.Time {
	if parseTime, err := time.ParseInLocation("20060102", s, loc); err == nil {
		return &parseTime
	}
	return nil
}

func getYmdHis01(s string, loc *time.Location) *time.Time {
	if parseTime, err := time.ParseInLocation("20060102150405", s, loc); err == nil {
		return &parseTime
	}
	return nil
}
